package com.zouxw.utils.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

public class EnhancedJsonTreeViewer extends JFrame {
    private JTree tree;
    private JTextArea jsonInputArea;
    private JTextField searchField;
    private JLabel statusLabel;
    private DefaultTreeModel treeModel;
    private Object rootJsonObject;

    // 右键菜单
    private JPopupMenu popupMenu;
    private JMenuItem addItemMenuItem;
    private JMenuItem addArrayItemMenuItem;
    private JMenuItem deleteMenuItem;

    // 值类型常量
    private static final String VALUE_TYPE_OBJECT = "OBJECT";
    private static final String VALUE_TYPE_ARRAY = "ARRAY";
    private static final String VALUE_TYPE_STRING = "STRING";
    private static final String VALUE_TYPE_NUMBER = "NUMBER";
    private static final String VALUE_TYPE_BOOLEAN = "BOOLEAN";
    private static final String VALUE_TYPE_NULL = "NULL";
    private static final String VALUE_TYPE_NESTED_JSON = "NESTED_JSON";
    private static final String VALUE_TYPE_UNKNOWN = "UNKNOWN";

    // 图标资源
    private final ImageIcon objectIcon = createIcon(Color.BLUE, 'O');
    private final ImageIcon arrayIcon = createIcon(Color.MAGENTA, 'A');
    private final ImageIcon stringIcon = createIcon(Color.GREEN, 'S');
    private final ImageIcon numberIcon = createIcon(Color.RED, 'N');
    private final ImageIcon booleanIcon = createIcon(Color.ORANGE, 'B');
    private final ImageIcon nullIcon = createIcon(Color.GRAY, '∅');
    private final ImageIcon nestedJsonIcon = createIcon(Color.CYAN, 'J');

    public EnhancedJsonTreeViewer() {
        setTitle("JSON树状查看器 - 增强版 (Fastjson)");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(900, 700);
        setLayout(new BorderLayout(5, 5));

        // 创建菜单栏
        createMenuBar();

        // 创建工具栏
        createToolBar();

        // 创建右键菜单
        createPopupMenu();

        // 创建输入区域
        jsonInputArea = new JTextArea();
        jsonInputArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
        JScrollPane inputScrollPane = new JScrollPane(jsonInputArea);
        inputScrollPane.setPreferredSize(new Dimension(900, 200));

        // 创建状态栏
        statusLabel = new JLabel("就绪");
        statusLabel.setBorder(BorderFactory.createEtchedBorder());

        // 创建树状显示区域
        tree = new JTree();
        tree.setFont(new Font("Dialog", Font.PLAIN, 14));
        tree.setCellRenderer(new JsonTreeCellRenderer());
        JScrollPane treeScrollPane = new JScrollPane(tree);

        // 添加鼠标双击监听器
        tree.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                    if (path != null) {
                        Object lastPathComponent = path.getLastPathComponent();
                        if (lastPathComponent instanceof JsonNode) {
                            JsonNode node = (JsonNode) lastPathComponent;
                            // 只允许编辑叶节点（没有子节点的节点）
                            if (node.isLeaf()) {
                                editNodeValue(node, path);
                            }
                        }
                    }
                }
            }
        });

        // 添加鼠标右键监听器
        tree.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                maybeShowPopup(e);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                maybeShowPopup(e);
            }

            private void maybeShowPopup(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                    if (path != null) {
                        tree.setSelectionPath(path);
                        Object lastPathComponent = path.getLastPathComponent();
                        if (lastPathComponent instanceof JsonNode) {
                            JsonNode node = (JsonNode) lastPathComponent;
                            // 根据节点类型启用/禁用菜单项
                            updatePopupMenuState(node);
                            popupMenu.show(e.getComponent(), e.getX(), e.getY());
                        }
                    }
                }
            }
        });

        // 布局组件
        JPanel topPanel = new JPanel(new BorderLayout(5, 5));
        topPanel.add(new JLabel("JSON输入:"), BorderLayout.NORTH);
        topPanel.add(inputScrollPane, BorderLayout.CENTER);

        add(topPanel, BorderLayout.NORTH);
        add(treeScrollPane, BorderLayout.CENTER);
        add(statusLabel, BorderLayout.SOUTH);

        // 添加输入监听器，实时验证JSON
        jsonInputArea.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                validateJson();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                validateJson();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                validateJson();
            }
        });

        // 添加解析按钮到工具栏
        JButton parseButton = new JButton("解析JSON");
        parseButton.addActionListener(e -> parseJson());
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(parseButton);
        add(buttonPanel, BorderLayout.SOUTH);

        setLocationRelativeTo(null);
    }

    private void createMenuBar() {
        JMenuBar menuBar = new JMenuBar();

        // 文件菜单
        JMenu fileMenu = new JMenu("文件");
        JMenuItem openItem = new JMenuItem("打开");
        JMenuItem saveItem = new JMenuItem("保存");
        JMenuItem exitItem = new JMenuItem("退出");

        openItem.addActionListener(this::openFile);
        saveItem.addActionListener(this::saveFile);
        exitItem.addActionListener(e -> System.exit(0));

        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);

        // 编辑菜单
        JMenu editMenu = new JMenu("编辑");
        JMenuItem formatItem = new JMenuItem("格式化");
        JMenuItem compressItem = new JMenuItem("压缩");

        formatItem.addActionListener(e -> formatJson(true));
        compressItem.addActionListener(e -> formatJson(false));

        editMenu.add(formatItem);
        editMenu.add(compressItem);

        menuBar.add(fileMenu);
        menuBar.add(editMenu);

        setJMenuBar(menuBar);
    }

    private void createToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);

        // 打开按钮
        JButton openButton = new JButton("打开");
        openButton.addActionListener(this::openFile);
        toolBar.add(openButton);

        // 保存按钮
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(this::saveFile);
        toolBar.add(saveButton);

        toolBar.addSeparator();

        // 格式化按钮
        JButton formatButton = new JButton("格式化");
        formatButton.addActionListener(e -> formatJson(true));
        toolBar.add(formatButton);

        // 压缩按钮
        JButton compressButton = new JButton("压缩");
        compressButton.addActionListener(e -> formatJson(false));
        toolBar.add(compressButton);

        toolBar.addSeparator();

        // 搜索组件 - 使用面板包装以确保正确显示
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 2));
        searchPanel.add(new JLabel("搜索:"));

        searchField = new JTextField(15);
        searchPanel.add(searchField);

        // 搜索按钮
        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> searchInTree());
        searchPanel.add(searchButton);

        // 清除搜索按钮
        JButton clearSearchButton = new JButton("清除");
        clearSearchButton.addActionListener(e -> {
            searchField.setText("");
            resetTreeHighlight();
        });
        searchPanel.add(clearSearchButton);

        // 将搜索面板添加到工具栏
        toolBar.add(searchPanel);

        add(toolBar, BorderLayout.NORTH);
    }

    private void createPopupMenu() {
        popupMenu = new JPopupMenu();

        // 添加对象属性菜单项
        addItemMenuItem = new JMenuItem("添加属性");
        addItemMenuItem.addActionListener(e -> addNewItem());
        popupMenu.add(addItemMenuItem);

        // 添加数组元素菜单项
        addArrayItemMenuItem = new JMenuItem("添加数组元素");
        addArrayItemMenuItem.addActionListener(e -> addNewArrayItem());
        popupMenu.add(addArrayItemMenuItem);

        popupMenu.addSeparator();

        // 删除菜单项
        deleteMenuItem = new JMenuItem("删除");
        deleteMenuItem.addActionListener(e -> deleteSelectedItem());
        popupMenu.add(deleteMenuItem);
    }

    private void updatePopupMenuState(JsonNode node) {
        String valueType = node.getValueType();

        // 根据节点类型启用/禁用菜单项
        if (VALUE_TYPE_OBJECT.equals(valueType)) {
            addItemMenuItem.setEnabled(true);
            addArrayItemMenuItem.setEnabled(false);
            deleteMenuItem.setEnabled(false); // 对象节点本身不能删除，但可以删除其属性
        } else if (VALUE_TYPE_ARRAY.equals(valueType)) {
            addItemMenuItem.setEnabled(false);
            addArrayItemMenuItem.setEnabled(true);
            deleteMenuItem.setEnabled(false); // 数组节点本身不能删除，但可以删除其元素
        } else {
            addItemMenuItem.setEnabled(false);
            addArrayItemMenuItem.setEnabled(false);
            deleteMenuItem.setEnabled(true); // 叶节点可以删除
        }

        // 根节点特殊处理
        if (node.getUserObject().equals("JSON Root")) {
            addItemMenuItem.setEnabled(false);
            addArrayItemMenuItem.setEnabled(false);
            deleteMenuItem.setEnabled(false);
        }
    }

    private void addNewItem() {
        TreePath selectionPath = tree.getSelectionPath();
        if (selectionPath == null) {
            JOptionPane.showMessageDialog(this, "请先选择一个对象节点", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        JsonNode selectedNode = (JsonNode) selectionPath.getLastPathComponent();
        if (!VALUE_TYPE_OBJECT.equals(selectedNode.getValueType())) {
            JOptionPane.showMessageDialog(this, "只能在对象节点上添加属性", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 输入键名
        String key = JOptionPane.showInputDialog(this, "请输入属性名:", "添加属性", JOptionPane.QUESTION_MESSAGE);
        if (key == null || key.trim().isEmpty()) {
            return;
        }

        // 输入值
        String value = JOptionPane.showInputDialog(this, "请输入属性值:", "添加属性", JOptionPane.QUESTION_MESSAGE);
        if (value == null) {
            return;
        }

        // 添加到JSON对象
        try {
            JSONObject jsonObject = (JSONObject) selectedNode.getJsonValue();
            jsonObject.put(key, value);

            // 更新树
            JsonNode newNode = new JsonNode(key + ": " + value, value, VALUE_TYPE_STRING);
            selectedNode.add(newNode);
            treeModel.reload(selectedNode);
            tree.expandPath(selectionPath);

            // 更新JSON文本
            updateJsonTextArea();

            statusLabel.setText("已添加属性: " + key);
            statusLabel.setForeground(Color.BLUE);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "添加属性时出错: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addNewArrayItem() {
        TreePath selectionPath = tree.getSelectionPath();
        if (selectionPath == null) {
            JOptionPane.showMessageDialog(this, "请先选择一个数组节点", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        JsonNode selectedNode = (JsonNode) selectionPath.getLastPathComponent();
        if (!VALUE_TYPE_ARRAY.equals(selectedNode.getValueType())) {
            JOptionPane.showMessageDialog(this, "只能在数组节点上添加元素", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 输入值
        String value = JOptionPane.showInputDialog(this, "请输入数组元素值:", "添加数组元素", JOptionPane.QUESTION_MESSAGE);
        if (value == null) {
            return;
        }

        // 添加到JSON数组
        try {
            JSONArray jsonArray = (JSONArray) selectedNode.getJsonValue();
            jsonArray.add(value);

            // 更新树
            int index = jsonArray.size() - 1;
            JsonNode newNode = new JsonNode("[" + index + "]: " + value, value, VALUE_TYPE_STRING);
            selectedNode.add(newNode);
            treeModel.reload(selectedNode);
            tree.expandPath(selectionPath);

            // 更新JSON文本
            updateJsonTextArea();

            statusLabel.setText("已添加数组元素");
            statusLabel.setForeground(Color.BLUE);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "添加数组元素时出错: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteSelectedItem() {
        TreePath selectionPath = tree.getSelectionPath();
        if (selectionPath == null) {
            JOptionPane.showMessageDialog(this, "请先选择一个节点", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        JsonNode selectedNode = (JsonNode) selectionPath.getLastPathComponent();
        if (selectedNode.getUserObject().equals("JSON Root")) {
            JOptionPane.showMessageDialog(this, "不能删除根节点", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 确认删除
        int result = JOptionPane.showConfirmDialog(this,
                "确定要删除选中的节点吗?",
                "确认删除",
                JOptionPane.YES_NO_OPTION);

        if (result != JOptionPane.YES_OPTION) {
            return;
        }

        try {
            // 获取父节点
            JsonNode parentNode = (JsonNode) selectedNode.getParent();

            // 从JSON结构中删除
            if (parentNode.getValueType().equals(VALUE_TYPE_OBJECT)) {
                JSONObject parentObject = (JSONObject) parentNode.getJsonValue();
                String key = selectedNode.toString();
                if (key.contains(": ")) {
                    key = key.substring(0, key.indexOf(": "));
                }
                parentObject.remove(key);
            } else if (parentNode.getValueType().equals(VALUE_TYPE_ARRAY)) {
                JSONArray parentArray = (JSONArray) parentNode.getJsonValue();
                String indexStr = selectedNode.toString();
                if (indexStr.contains(": ")) {
                    indexStr = indexStr.substring(0, indexStr.indexOf(": "));
                }
                indexStr = indexStr.replace("[", "").replace("]", "");
                int index = Integer.parseInt(indexStr);
                parentArray.remove(index);
            }

            // 从树中删除
            parentNode.remove(selectedNode);
            treeModel.reload(parentNode);

            // 更新JSON文本
            updateJsonTextArea();

            statusLabel.setText("已删除节点");
            statusLabel.setForeground(Color.BLUE);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "删除节点时出错: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void validateJson() {
        String jsonString = jsonInputArea.getText().trim();
        if (jsonString.isEmpty()) {
            statusLabel.setText("就绪");
            return;
        }

        try {
            JSON.parse(jsonString);
            statusLabel.setText("JSON格式正确");
            statusLabel.setForeground(Color.BLACK);
        } catch (Exception ex) {
            statusLabel.setText("JSON格式错误: " + ex.getMessage());
            statusLabel.setForeground(Color.RED);
        }
    }

    private void parseJson() {
        String jsonString = jsonInputArea.getText().trim();
        if (jsonString.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入JSON字符串", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            rootJsonObject = JSON.parse(jsonString);
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("JSON Root");
            buildTree(rootNode, rootJsonObject, "");

            treeModel = new DefaultTreeModel(rootNode);
            tree.setModel(treeModel);

            // 展开所有节点
            expandAllNodes(tree, 0, tree.getRowCount());

            statusLabel.setText("JSON解析成功");
            statusLabel.setForeground(Color.BLACK);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "JSON解析错误: " + ex.getMessage(),
                    "解析错误", JOptionPane.ERROR_MESSAGE);
            statusLabel.setText("JSON解析错误: " + ex.getMessage());
            statusLabel.setForeground(Color.RED);
            ex.printStackTrace();
        }
    }

    private void buildTree(DefaultMutableTreeNode parent, Object jsonValue, String key) {
        if (jsonValue instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) jsonValue;
            JsonNode node = new JsonNode(key.isEmpty() ? "{}" : key, jsonValue, VALUE_TYPE_OBJECT);
            parent.add(node);

            // 使用forEach和lambda表达式处理对象属性
            jsonObject.entrySet().forEach(entry ->
                    buildTree(node, entry.getValue(), entry.getKey())
            );
        } else if (jsonValue instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) jsonValue;
            JsonNode node = new JsonNode(key.isEmpty() ? "[]" : key, jsonValue, VALUE_TYPE_ARRAY);
            parent.add(node);

            // 使用IntStream处理数组元素
            IntStream.range(0, jsonArray.size()).forEach(i ->
                    buildTree(node, jsonArray.get(i), "[" + i + "]")
            );
        } else {
            // 基本值类型 - 检查是否是嵌套的JSON字符串
            if (jsonValue instanceof String) {
                String stringValue = (String) jsonValue;

                // 尝试解析字符串是否为嵌套的JSON
                try {
                    Object nestedJson = JSON.parse(stringValue);
                    if (nestedJson instanceof JSONObject || nestedJson instanceof JSONArray) {
                        // 这是一个嵌套的JSON字符串
                        JsonNode node = new JsonNode(key, stringValue, VALUE_TYPE_NESTED_JSON);
                        parent.add(node);

                        // 递归解析嵌套的JSON
                        buildTree(node, nestedJson, "");
                        return;
                    }
                } catch (Exception e) {
                    // 不是有效的JSON字符串，继续作为普通字符串处理
                }
            }

            // 普通值类型
            String value = String.valueOf(jsonValue);
            String valueType = getValueType(jsonValue);
            parent.add(new JsonNode(key.isEmpty() ? value : key + ": " + value, jsonValue, valueType));
        }
    }

    private String getValueType(Object value) {
        if (value instanceof JSONObject) return VALUE_TYPE_OBJECT;
        if (value instanceof JSONArray) return VALUE_TYPE_ARRAY;
        if (value instanceof String) return VALUE_TYPE_STRING;
        if (value instanceof Number) return VALUE_TYPE_NUMBER;
        if (value instanceof Boolean) return VALUE_TYPE_BOOLEAN;
        if (value == null) return VALUE_TYPE_NULL;
        return VALUE_TYPE_UNKNOWN;
    }

    private void openFile(ActionEvent e) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("JSON文件", "json"));

        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                String content = new String(Files.readAllBytes(Paths.get(fileChooser.getSelectedFile().getPath())));
                jsonInputArea.setText(content);
                parseJson();
                statusLabel.setText("已打开文件: " + fileChooser.getSelectedFile().getName());
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "读取文件错误: " + ex.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
                statusLabel.setText("读取文件错误: " + ex.getMessage());
                statusLabel.setForeground(Color.RED);
            }
        }
    }

    private void saveFile(ActionEvent e) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("JSON文件", "json"));

        int result = fileChooser.showSaveDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                String fileName = fileChooser.getSelectedFile().getPath();
                if (!fileName.toLowerCase().endsWith(".json")) {
                    fileName += ".json";
                }

                Files.write(Paths.get(fileName), jsonInputArea.getText().getBytes());
                statusLabel.setText("已保存文件: " + fileChooser.getSelectedFile().getName());
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "保存文件错误: " + ex.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
                statusLabel.setText("保存文件错误: " + ex.getMessage());
                statusLabel.setForeground(Color.RED);
            }
        }
    }

    private void formatJson(boolean pretty) {
        String jsonString = jsonInputArea.getText().trim();
        if (jsonString.isEmpty()) {
            return;
        }

        try {
            Object jsonObject = JSON.parse(jsonString);

            String formattedJson = pretty ?
                    JSON.toJSONString(jsonObject, true) :
                    JSON.toJSONString(jsonObject);

            jsonInputArea.setText(formattedJson);
            parseJson();
            statusLabel.setText(pretty ? "已格式化JSON" : "已压缩JSON");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "JSON处理错误: " + ex.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
            statusLabel.setText("JSON处理错误: " + ex.getMessage());
            statusLabel.setForeground(Color.RED);
        }
    }

    private void searchInTree() {
        if (treeModel == null) {
            JOptionPane.showMessageDialog(this, "请先解析JSON", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String searchText = searchField.getText().trim();
        if (searchText.isEmpty()) {
            resetTreeHighlight();
            return;
        }

        // 重置所有节点的高亮状态
        resetTreeHighlight();

        // 搜索匹配的节点
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeModel.getRoot();
        Enumeration<?> e = root.depthFirstEnumeration();
        Pattern pattern = Pattern.compile(Pattern.quote(searchText), Pattern.CASE_INSENSITIVE);

        boolean found = false;
        while (e.hasMoreElements()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
            if (node instanceof JsonNode) {
                JsonNode jsonNode = (JsonNode) node;
                if (pattern.matcher(jsonNode.toString()).find()) {
                    jsonNode.setHighlighted(true);
                    found = true;

                    // 展开到该节点
                    TreeNode[] path = jsonNode.getPath();
                    tree.expandPath(new javax.swing.tree.TreePath(path));

                    // 滚动到该节点
                    tree.scrollPathToVisible(new javax.swing.tree.TreePath(path));
                }
            }
        }

        if (!found) {
            statusLabel.setText("未找到匹配项: " + searchText);
            statusLabel.setForeground(Color.ORANGE);
        } else {
            statusLabel.setText("找到匹配项: " + searchText);
            statusLabel.setForeground(Color.BLUE);
        }

        // 刷新树显示
        tree.repaint();
    }

    private void resetTreeHighlight() {
        if (treeModel == null) return;

        DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeModel.getRoot();
        Enumeration<?> e = root.depthFirstEnumeration();

        while (e.hasMoreElements()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
            if (node instanceof JsonNode) {
                ((JsonNode) node).setHighlighted(false);
            }
        }

        // 刷新树显示
        tree.repaint();
        statusLabel.setText("就绪");
        statusLabel.setForeground(Color.BLACK);
    }

    // 编辑节点值的方法
    private void editNodeValue(JsonNode node, TreePath path) {
        String currentValue = node.getUserObject().toString();
        String valueType = node.getValueType();

        // 根据值类型创建不同的编辑对话框
        Object newValue = null;

        if (VALUE_TYPE_STRING.equals(valueType) || VALUE_TYPE_NESTED_JSON.equals(valueType)) {
            // 字符串类型 - 使用文本区域编辑
            JTextArea textArea = new JTextArea(currentValue, 10, 30);
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);

            int result = JOptionPane.showConfirmDialog(this,
                    new JScrollPane(textArea),
                    "编辑值",
                    JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE);

            if (result == JOptionPane.OK_OPTION) {
                newValue = textArea.getText();
            }
        } else if (VALUE_TYPE_NUMBER.equals(valueType)) {
            // 数字类型 - 使用文本字段编辑
            String input = JOptionPane.showInputDialog(this,
                    "编辑数值:",
                    currentValue);

            if (input != null) {
                try {
                    // 尝试解析为数字
                    if (input.contains(".")) {
                        newValue = Double.parseDouble(input);
                    } else {
                        newValue = Long.parseLong(input);
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(this,
                            "无效的数字格式: " + input,
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
        } else if (VALUE_TYPE_BOOLEAN.equals(valueType)) {
            // 布尔类型 - 使用选项对话框
            Object[] options = {"true", "false"};
            int result = JOptionPane.showOptionDialog(this,
                    "选择布尔值:",
                    "编辑布尔值",
                    JOptionPane.DEFAULT_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    currentValue);

            if (result >= 0) {
                newValue = Boolean.parseBoolean(options[result].toString());
            }
        } else if (VALUE_TYPE_NULL.equals(valueType)) {
            // null值 - 不能编辑，显示消息
            JOptionPane.showMessageDialog(this,
                    "null值不能编辑",
                    "信息",
                    JOptionPane.INFORMATION_MESSAGE);
            return;
        } else {
            // 其他类型 - 使用文本字段编辑
            String input = JOptionPane.showInputDialog(this,
                    "编辑值:",
                    currentValue);

            if (input != null) {
                newValue = input;
            }
        }

        // 如果用户提供了新值，更新节点和JSON
        if (newValue != null) {
            updateNodeValue(node, path, newValue);
        }
    }

    // 更新节点值并刷新树
    private void updateNodeValue(JsonNode node, TreePath path, Object newValue) {
        // 更新节点显示文本
        String displayText = node.toString();
        if (displayText.contains(": ")) {
            // 如果是键值对形式，保留键部分
            String key = displayText.substring(0, displayText.indexOf(": "));
            node.setUserObject(key + ": " + newValue.toString());
        } else {
            // 如果是纯值，直接更新
            node.setUserObject(newValue.toString());
        }

        // 更新节点的原始值
        node.setJsonValue(newValue);

        // 更新JSON数据结构
        updateJsonStructure(node, path, newValue);

        // 刷新树显示
        treeModel.nodeChanged(node);
        tree.repaint();

        // 更新JSON文本区域
        updateJsonTextArea();

        statusLabel.setText("值已更新");
        statusLabel.setForeground(Color.BLUE);
    }

    // 更新JSON数据结构
    private void updateJsonStructure(JsonNode node, TreePath path, Object newValue) {
        try {
            // 获取节点的路径
            Object[] pathArray = path.getPath();

            // 从根节点开始遍历路径
            Object current = rootJsonObject;
            for (int i = 1; i < pathArray.length - 1; i++) {
                JsonNode pathNode = (JsonNode) pathArray[i];
                String nodeName = pathNode.toString();

                if (current instanceof JSONObject) {
                    JSONObject obj = (JSONObject) current;

                    // 检查节点名是否是键
                    if (obj.containsKey(nodeName)) {
                        current = obj.get(nodeName);
                    } else {
                        // 可能是数组索引
                        try {
                            int index = Integer.parseInt(nodeName.replace("[", "").replace("]", ""));
                            if (current instanceof JSONArray) {
                                JSONArray arr = (JSONArray) current;
                                if (index >= 0 && index < arr.size()) {
                                    current = arr.get(index);
                                }
                            }
                        } catch (NumberFormatException e) {
                            // 不是数组索引，继续处理
                        }
                    }
                } else if (current instanceof JSONArray) {
                    JSONArray arr = (JSONArray) current;
                    try {
                        int index = Integer.parseInt(nodeName.replace("[", "").replace("]", ""));
                        if (index >= 0 && index < arr.size()) {
                            current = arr.get(index);
                        }
                    } catch (NumberFormatException e) {
                        // 不是数组索引，忽略
                    }
                }
            }

            // 更新值
            JsonNode parentNode = (JsonNode) pathArray[pathArray.length - 2];
            String nodeName = node.toString();

            if (nodeName.contains(": ")) {
                nodeName = nodeName.substring(0, nodeName.indexOf(": "));
            }

            if (current instanceof JSONObject) {
                JSONObject obj = (JSONObject) current;
                obj.put(nodeName, newValue);
            } else if (current instanceof JSONArray) {
                JSONArray arr = (JSONArray) current;
                try {
                    int index = Integer.parseInt(nodeName.replace("[", "").replace("]", ""));
                    if (index >= 0 && index < arr.size()) {
                        arr.set(index, newValue);
                    }
                } catch (NumberFormatException e) {
                    // 不是数组索引，忽略
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "更新JSON结构时出错: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    // 更新JSON文本区域
    private void updateJsonTextArea() {
        try {
            String formattedJson = JSON.toJSONString(rootJsonObject, true);
            jsonInputArea.setText(formattedJson);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "更新JSON文本时出错: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    // 展开所有树节点
    private void expandAllNodes(JTree tree, int startingIndex, int rowCount) {
        for (int i = startingIndex; i < rowCount; ++i) {
            tree.expandRow(i);
        }

        if (tree.getRowCount() != rowCount) {
            expandAllNodes(tree, rowCount, tree.getRowCount());
        }
    }

    // 创建简单的图标
    private ImageIcon createIcon(Color color, char letter) {
        int size = 16;
        java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(size, size, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = image.createGraphics();

        g2.setColor(color);
        g2.fillOval(1, 1, size-2, size-2);

        g2.setColor(Color.WHITE);
        g2.setFont(new Font("SansSerif", Font.BOLD, 12));
        g2.drawString(String.valueOf(letter), 5, 13);

        g2.dispose();
        return new ImageIcon(image);
    }

    // 自定义树节点类，用于存储JSON值和显示状态
    class JsonNode extends DefaultMutableTreeNode {
        private Object jsonValue;
        private final String valueType;
        private boolean highlighted = false;

        public JsonNode(String text, Object jsonValue, String valueType) {
            super(text);
            this.jsonValue = jsonValue;
            this.valueType = valueType;
        }

        public Object getJsonValue() {
            return jsonValue;
        }

        public void setJsonValue(Object jsonValue) {
            this.jsonValue = jsonValue;
        }

        public String getValueType() {
            return valueType;
        }

        public boolean isHighlighted() {
            return highlighted;
        }

        public void setHighlighted(boolean highlighted) {
            this.highlighted = highlighted;
        }
    }

    // 自定义树单元格渲染器
    class JsonTreeCellRenderer implements TreeCellRenderer {
        private final JLabel label = new JLabel();

        public JsonTreeCellRenderer() {
            label.setOpaque(true);
            label.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
        }

        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                                      boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            if (value instanceof JsonNode) {
                JsonNode node = (JsonNode) value;

                // 设置文本
                label.setText(node.toString());

                // 设置图标
                String valueType = node.getValueType();
                if (VALUE_TYPE_OBJECT.equals(valueType)) {
                    label.setIcon(objectIcon);
                } else if (VALUE_TYPE_ARRAY.equals(valueType)) {
                    label.setIcon(arrayIcon);
                } else if (VALUE_TYPE_STRING.equals(valueType)) {
                    label.setIcon(stringIcon);
                } else if (VALUE_TYPE_NUMBER.equals(valueType)) {
                    label.setIcon(numberIcon);
                } else if (VALUE_TYPE_BOOLEAN.equals(valueType)) {
                    label.setIcon(booleanIcon);
                } else if (VALUE_TYPE_NULL.equals(valueType)) {
                    label.setIcon(nullIcon);
                } else if (VALUE_TYPE_NESTED_JSON.equals(valueType)) {
                    label.setIcon(nestedJsonIcon);
                } else {
                    label.setIcon(null);
                }

                // 设置高亮
                if (node.isHighlighted()) {
                    label.setBackground(Color.YELLOW);
                    label.setForeground(Color.BLACK);
                    label.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
                } else if (selected) {
                    label.setBackground(UIManager.getColor("Tree.selectionBackground"));
                    label.setForeground(UIManager.getColor("Tree.selectionForeground"));
                } else {
                    label.setBackground(UIManager.getColor("Tree.textBackground"));
                    label.setForeground(UIManager.getColor("Tree.textForeground"));
                }
            } else {
                label.setText(value.toString());
                label.setIcon(null);

                if (selected) {
                    label.setBackground(UIManager.getColor("Tree.selectionBackground"));
                    label.setForeground(UIManager.getColor("Tree.selectionForeground"));
                } else {
                    label.setBackground(UIManager.getColor("Tree.textBackground"));
                    label.setForeground(UIManager.getColor("Tree.textForeground"));
                }
            }

            return label;
        }
    }

    public static void main(String[] args) {
        // 使用SwingUtilities.invokeLater确保线程安全
        SwingUtilities.invokeLater(() -> {
            EnhancedJsonTreeViewer viewer = new EnhancedJsonTreeViewer();
            viewer.setVisible(true);

            // 预置示例JSON，包含嵌套的JSON字符串
            String sampleJson = "{\n" +
                    "  \"name\": \"John Doe\",\n" +
                    "  \"age\": 30,\n" +
                    "  \"isStudent\": false,\n" +
                    "  \"address\": {\n" +
                    "    \"street\": \"123 Main St\",\n" +
                    "    \"city\": \"Anytown\",\n" +
                    "    \"zip\": \"12345\"\n" +
                    "  },\n" +
                    "  \"phoneNumbers\": [\n" +
                    "    {\n" +
                    "      \"type\": \"home\",\n" +
                    "      \"number\": \"555-1234\"\n" +
                    "    },\n" +
                    "    {\n" +
                    "      \"type\": \"work\",\n" +
                    "      \"number\": \"555-5678\"\n" +
                    "    }\n" +
                    "  ],\n" +
                    "  \"children\": [],\n" +
                    "  \"scores\": [85, 92, 78, 90],\n" +
                    "  \"metadata\": null,\n" +
                    "  \"nestedJson\": \"{\\\"key1\\\": \\\"value1\\\", \\\"key2\\\": {\\\"nestedKey\\\": \\\"nestedValue\\\"}}\",\n" +
                    "  \"nestedArray\": \"[\\\"item1\\\", \\\"item2\\\", {\\\"objInArray\\\": \\\"value\\\"}]\",\n" +
                    "  \"mixedData\": {\n" +
                    "    \"regularString\": \"just a string\",\n" +
                    "    \"jsonString\": \"{\\\"internalKey\\\": \\\"internalValue\\\"}\",\n" +
                    "    \"numberValue\": 42\n" +
                    "  }\n" +
                    "}";

            viewer.jsonInputArea.setText(sampleJson);
        });
    }
}